<template>
	
	<view class="content">
		<QSInput :name="name" titleColor="#0000" variableName="input"  layout="column" title="日志标题" v-model="LogObj.title"></QSInput>
		<QSTextarea :name="name" titleColor="#0000;" textareaWidth="100" textareaHeight="15" variableName="textarea" layout="column" title="日志内容" v-model="LogObj.content"></QSTextarea>
		<view style="font-size: 15px;">附件</view>
		<view>
			<button class="primary" type="warn" @click="openFile()" >选择文件</button>
		 </view>
		 
		<view>
			<view  style="color: #0077AA;" v-for="(file,index) in tempFileList" :key="index">{{file.name}}
			<span style="margin-left: 20px;"><uni-icons @click="delFile(index)" type="closeempty" size="30" ></uni-icons></span>
			</view>
		</view>
		
		<view style="margin-top: 10%;">
			<button type="primary" @click="saveOrUpdate">{{buttonText}}</button>
		</view>
		
	
	</view>
</template>

<script>
	import QSApp from '@/components/QS-inputs-split/js/app.js'
	import {
		mapState
	} from 'vuex'
	import loginjs from '../../login.js' 
	import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue'
	export default{
			computed: mapState(['baseUrl']),
			components:{uniIcons},
		data(){
			return{
				form: {
					input: '',
					textarea: '',
					infinitePics: [],
					},
				logTitle:'',
				filename: [],
				Authorization:"",
				filePath:[],
				tempFileList:[],
				logworkid:null,
				path:'',
				buttonText:"保存",
				LogObj:{
					title:'',
					content:'',
					code:[]
				}
			
			}
		},
		onReady() {
			this.getPickerData();
		},
		onLoad(options) {
			//检测用户是否登录
				var uNameAndAuth= loginjs.checkLogin()
				//用户名和认证信息的组合
				if(uNameAndAuth==null){
					return
				}
				 uNameAndAuth= uNameAndAuth.split("/")
				//this.user=uNameAndAuth[0]
				this.Authorization=uNameAndAuth[1]
			if(options.logId==null){
				return
			}
			//console.log(options.logId)
			//如果穿过来存在id则根据id查询该条数据的详细
			this.logworkid=options.logId
			this.buttonText="修改"
			this.getLogByLogId(options.logId)
		},
		
		methods:{
			toAddWork(){
				uni.navigateTo({
					url:'logindex'
				})
			},
			/* 点击提交按钮， */
			saveOrUpdate(){
				var jsoncode=JSON.stringify(this.tempFileList)
				this.LogObj.code=jsoncode
				if(this.LogObj.content==''){
					uni.showToast({
						title:"请输入日志内容",
						duration:2000,
						icon:"none"
					})
					return
				}
				/* 判断id是否存在如存在则为更新操作 */
			if(this.logworkid!=null){
				/* 更新操作 */
				uni.request({
					url:this.baseUrl+"api/logWork/"+this.logworkid,
					method:"PUT",
					data:this.LogObj,
					header: {
					"Authorization": this.Authorization,
					},
					 success: (result) => {
						 if(result.data.code==200){
							uni.showToast({
								title:"修改成功",
								duration:2000,
								icon:"none"
							});
							uni.switchTab({
							    url: 'logindex'
							});
						 }else{
							uni.showToast({
								title:"修改失败",
								duration:2000,
								icon:"none"
							})  
						 }
					 	
					 },
					 fail: (result) => {
					 	uni.showToast({
					 		title:"修改失败",
							duration:2000,
							icon:"none"
					 	})
					 }
					})
			}else{
				uni.request({
					url:this.baseUrl+"api/logWork/add",
					method:"POST",
					data:this.LogObj,
					header: {
					"Authorization": this.Authorization,
					},
					 success: (result) => {
						 if(result.data.code==200){
							uni.showToast({
								title:"保存成功",
								duration:2000,
								icon:"none"
							});
							uni.switchTab({
							    url: 'logindex',
							});
						 }
					 	
					 },
					 fail: (result) => {
					 	uni.showToast({
					 		title:result,
							duration:2000,
							icon:"none"
					 	})
					 }
					})
				}
			},
			
			/* 点击删除上传的文件 */
			delFile(index){
				this.tempFileList.splice(index,1)
			},
			
			/* 根据id查询该条数据的详细 */
			getLogByLogId(logId){
				uni.request({
					url:this.baseUrl+"api/logWork/"+logId,
					method:"GET",
					header: {
					"Authorization": this.Authorization,
					},
					success:(res)=>{
						console.log(res)
						if(res.data.code==200){
							//获取数据成功
							this.LogObj.title=res.data.data.title
						//	console.log(this.LogObj.title)
							this.LogObj.content=res.data.data.content
							this.tempFileList=JSON.parse(res.data.data.code)
						}else{
							//获取数据失败
							uni.showToast({
								title:"获取数据失败",
								icon:"none",
								duration:2000
							})
						}
					}
				})
			},
			
			openPopup() {
				this.$refs.popup.open()
			},
			closePopup() {
				this.$refs.popup.close()
			},
			resultPath(e) {
				this.path = e
				
				console.log(this.path)
				
				/* 上传文件 */
				uni.uploadFile({
				            url: this.baseUrl+'api/upload', //仅为示例，非真实的接口地址
				            filePath: 'file://'+this.path,
							name: 'file',
							//fileType:"image",
				            success: (uploadFileRes) => {
				               var result=JSON.parse(uploadFileRes.data);
							   if(result.state="SUCCESS"){
								   /* 上传成功,将url 和 title 存到本地,整个页面提交时再把所有数据拼装存入数据库*/
								  uni.showToast({
								  	title:"文件上传成功",
									icon:"none",
									duration:1000
									
								  })
								   var obj={}
								   obj["name"]=result.title
								   obj["url"]=result.url
								   this.tempFileList.push(obj)
								  // this.LogObj.code.push(obj)
							   }else{
								  uni.showToast({
								  	title:"文件上传失败",
									icon:"none",
									duration:2000
								  })
							   }
							   
				            },
							fail(e) {
								console.log(e)
							}
				        });
				
			},
			
			
			
			/* 打开本地文件管理器 */
			openFile() {
				// #ifdef APP-PLUS
				if (plus.os.name.toLowerCase() != "android") {
					uni.showModal({
						title: '提示',
						content: '仅支持Android平台',
						success: function(res) {}
					});
					return false
				}
				let that = this
				// java 代码来自 http://www.cnblogs.com/panhouye/archive/2017/04/23/6751710.html
				let main = plus.android.runtimeMainActivity();
				let Intent = plus.android.importClass("android.content.Intent");
			
				// 
				let fileIntent = new Intent(Intent.ACTION_GET_CONTENT)
				//fileIntent.setType(“image/*”);//选择图片
				//fileIntent.setType(“audio/*”); //选择音频
				//fileIntent.setType(“video/*”); //选择视频 （mp4 3gp 是android支持的视频格式）
				//fileIntent.setType(“video/*;image/*”);//同时选择视频和图片
				fileIntent.setType("*/*"); //无类型限制
				fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
				main.startActivityForResult(fileIntent, 1);
				// 获取回调
				main.onActivityResult = function(requestCode, resultCode, data) {
					let Activity = plus.android.importClass("android.app.Activity");
					let ContentUris = plus.android.importClass("android.content.ContentUris");
					let Cursor = plus.android.importClass("android.database.Cursor");
					let Uri = plus.android.importClass("android.net.Uri");
					let Build = plus.android.importClass("android.os.Build");
					let Environment = plus.android.importClass("android.os.Environment");
					let DocumentsContract = plus.android.importClass("android.provider.DocumentsContract");
					let MediaStore = plus.android.importClass("android.provider.MediaStore");
					// 给系统导入 contentResolver
					let contentResolver = main.getContentResolver()
					plus.android.importClass(contentResolver);
					// 返回路径
					let path = '';
					if (resultCode == Activity.RESULT_OK) {
						let uri = data.getData()
						if ("file" == uri.getScheme().toLowerCase()) { //使用第三方应用打开
							path = uri.getPath();
							return;
						}
						if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { //4.4以后
							path = getPath(this, uri);
						} else { //4.4以下下系统调用方法
							path = getRealPathFromURI(uri)
						}
						// 回调
						that.resultPath(path)
						// that.$emit('result', path)
					}
					// 4.4 以上 从Uri 获取文件绝对路径
					function getPath(context, uri) {
						let isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
						let scheme = uri.getScheme().toLowerCase()
						if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
							// ExternalStorageProvider
							if (isExternalStorageDocument(uri)) {
								let docId = DocumentsContract.getDocumentId(uri);
								let split = docId.split(":");
								let type = split[0];
								// 如果是手机内部存储
								if ("primary" == type.toLowerCase()) {
									return Environment.getExternalStorageDirectory() + "/" + split[1];
								} else {
									return '/storage/' + type + "/" + split[1]; 
								}
							}
							// DownloadsProvider
							else if (isDownloadsDocument(uri)) {
								let id = DocumentsContract.getDocumentId(uri);
								let split = id.split(":");
								return split[1]
								// console.log(id)
								// let contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), id);
								// return getDataColumn(context, contentUri, null, null);
							}
							// MediaProvider
							else if (isMediaDocument(uri)) {
								let docId = DocumentsContract.getDocumentId(uri);
								let split = docId.split(":");
								let type = split[0];
								let contentUri = null;
								if ("image" == type.toLowerCase()) {
									contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
								} else if ("video" == type.toLowerCase()) {
									contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
								} else if ("audio" == type.toLowerCase()) {
									contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
								}
								let selection = "_id=?";
								let selectionArgs = [split[1]];
								return getDataColumn(context, contentUri, selection, selectionArgs);
							}
						}
						// MediaStore (and general)
						else if ("content" == scheme) {
							return getDataColumn(context, uri, null, null);
						}
						// File
						else if ("file" == scheme) {
							return uri.getPath();
						}
					}
					// 4.4 以下 获取 绝对路径
					function getRealPathFromURI(uri) {
						let res = null
						let proj = [MediaStore.Images.Media.DATA]
						let cursor = contentResolver.query(uri, proj, null, null, null);
						if (null != cursor && cursor.moveToFirst()) {;
							let column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
							res = cursor.getString(column_index);
							cursor.close();
						}
						return res;
					}
					// 通过uri 查找出绝对路径
					function getDataColumn(context, uri, selection, selectionArgs) {
						let cursor = null;
						let column = "_data";
						let projection = [column];
						// let contentResolver = context.getContentResolver()
						// plus.android.importClass(contentResolver);
						cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);
						if (cursor != null && cursor.moveToFirst()) {
							let column_index = cursor.getColumnIndexOrThrow(column);
							return cursor.getString(column_index);
						}
					}
			
					function isExternalStorageDocument(uri) {
						return "com.android.externalstorage.documents" == uri.getAuthority() ? true : false
					}
			
					function isDownloadsDocument(uri) {
						return "com.android.providers.downloads.documents" == uri.getAuthority() ? true : false
					}
			
					function isMediaDocument(uri) {
						return "com.android.providers.media.documents" == uri.getAuthority() ? true : false
					}
				}
				// #endif
				// #ifndef APP-PLUS
				uni.showModal({
					title: '提示',
					content: '仅支持Android平台',
					success: function(res) {
			
					}
				});
				// #endif
			},
			
			/* 上传 文件*/
			upload(){
				//console.log(this.path)
				
			},

			
		},

				
	}
</script>

<style>
</style>
